package com.itheima.web;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.Service.CategoryService;
import com.itheima.bean.Category;
import com.itheima.common.PageParam;
import com.itheima.common.R;

import com.itheima.dao.CategoryDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/category")
@RestController
public class CategoryController {

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private CategoryDao categoryDao;

    /**
     * 添加分类
     * @param category
     * @return
     */
    @PostMapping
    public R add(@RequestBody Category category){

        //调用Service
        int row = categoryService.add(category);

        if(row > 0){
            return R.success("添加成功！");
        }

        return R.error("添加失败！");
    }


    /**
     * 分类_分页查询
     * @param pageParam
     * @return
     */
    @GetMapping("/page")
    public R findPage(PageParam pageParam){

        //调用Service
        IPage<Category> page = categoryService.findPage(pageParam);

        return R.success(page);
    }

    /**
     * 删除分类
     * @param id
     * @return
     */
    @DeleteMapping
    public R delete(long id){

        //调用Service
        int row = categoryService.delete(id);

        if(row > 0){
            return R.success("删除成功！");
        }

        return R.error("删除失败！");
    }

    /**
     * 更新分类
     * @param category
     * @return
     */
    @PutMapping
    public R update(@RequestBody Category category){

        //调用Service
        int row = categoryService.update(category);

        if(row > 0){
            return R.success("更新成功！");
        }

        return R.error("更新失败！");
    }

    /**
     * 查询菜品分类   这里多设置了一个判断条件，如果type为null 则查询所有分类
     * @param type
     * @return
     */
    @GetMapping("/list")
    public R findList(Integer type){
        LambdaQueryWrapper<Category> clqw = new LambdaQueryWrapper<>();
        clqw.eq(type !=null,Category::getType,type);
        List<Category> categories = categoryDao.selectList(clqw);
        if (categories!=null){
            return R.success(categories);
        }
        return R.error("查询菜品分类失败");
    }
}
